package com.dpj.ucenter.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dpj.commonutils.JwtUtils;
import com.dpj.ucenter.entity.Member;
import com.dpj.ucenter.mapper.MemberMapper;
import com.dpj.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dpj.ucenter.utils.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-02-04
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    //登录的方法
    @Override
    public String login(Member member) {
        //获取登录手机号和密码
        String mobile = member.getMobile();
        String password = member.getPassword();

        //手机号和密码非空判断
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            try {
                throw new Exception("登录出错");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //判断手机号是否正确
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Member mobileMember = baseMapper.selectOne(wrapper);
        //判断查询对象是否为空
        if(mobileMember == null) {//没有这个手机号
            try {
                throw new Exception("登录失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据库密码进行比较
        //加密方式 MD5
        if(!MD5.encrypt(password).equals(mobileMember.getPassword())) {
            try {
                throw new Exception("登录失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //判断用户是否禁用
        if(mobileMember.getIsDisabled()) {
            try {
                throw new Exception("登录失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //登录成功
        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(mobileMember.getId(), mobileMember.getNickname());
        return jwtToken;
    }
    //查询某一天注册人数
    @Override
    public Integer countRegisterDay(String day) {
        return null;
    }

    @Override
    public Member getOpenIdMember(String openid) {
        QueryWrapper<Member> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("openid",openid);

        Member member = this.baseMapper.selectOne(queryWrapper);
        return  member;
    }
}
